package com.zxl.muban.shiro;

import com.zxl.muban.entity.User;
import com.zxl.muban.service.UserService;
import com.zxl.muban.util.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * web端登录的Realm管理
 */
public class WebShiroRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
	/**
     * 授权权限
     * 在ShiroRealm统一处理，这里不做处理
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    public String getName() {
        return LoginType.USER_WEB_PASSWORD.getType();
    }

	/**
     * 身份认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户的输入的账号.
        String loginName = (String) authenticationToken.getPrincipal();
        //通过登录名从数据库中查找 User对象，如果找到进行验证
        User user = userService.getUserByName(loginName);
        //判断账号是否存在
        if (user == null ) {
            throw new LockedAccountException("当前账号不存在");
        }
        // 后台登录判断用户是否是管理员/超级管理员
//        if (user.getAdmin().equals(User.ADMIN_NORMAL)) {
//            // 校验正常用户有没有后台登录权限
//            if (User.STATUS_CLOSE.equals(user.getStatus())){
//                throw new LockedAccountException("没有相关权限进入后台请联系管理员开通权限");
//            }
//        }
        //进行验证
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,                                  //用户名
                user.getPassword(),                    //密码
                ByteSource.Util.bytes(user.getSalt()),//密码盐值
                getName()
        );
        //验证成功开始踢人(清除缓存和Session)
        ShiroUtils.deleteCache(loginName,LoginType.USER_WEB_PASSWORD.getType());
        return authenticationInfo;
    }
}
